const Router = require('koa-router');
const koaBody = require('koa-body');
const views = require('koa-views');
const cors = require('../lib/kcors');
const path = require('path');
const fs = require('fs');
const {Passport} = require('../lib/passport.js');
const {TYPE} = require('./constant/user.js');
/**
 *@param {object} app - koa app 
 */

module.exports = app => {
    const router = new Router({
		// prefix: '/front'
	});
    router.use(cors({
		origin: ['http://localhost:5173','http://fmsc.klcxy.com'],
		credentials: true
	}));
	// 检查页面权限
    // router.use(Passport.intercept({
	// 	rules: [
	// 		`888:/orderForGoods`,
	// 		`1:/orderForGoods|list`,
	// 		`888:/user`,
	// 		`1:/user|get`,
	// 		`0:/user|login`,
	// 		`0:/client`,
	// 		`3:/client|list`,
	// 	]
	// }))

	router.use(koaBody({
		multipart: true,	// 支持文件上传
		// encoding: "gzip",
		formLimit: '5mb',	// 最多支持上传1M
		jsonLimit: '5mb',
		formidable: {
			uploadDir:path.join( __dirname,'../public/temporary'),// 文件上传目，
			keepExtensions: true, // 保持文件的后缀
			maxFileSize: 5*1024*1024,	// 上传限制在 5M 以内
			onFileBegin(name,file){
				console.log(name);
			}
		},
		
	}))
	
    // 加载模板引擎
    router.use(views(path.join(__dirname, './view'), {
        extension: 'ejs'
    }))

	// 加载常量
	let constant = {}
	for (let fname of fs.readdirSync(__dirname + '/constant')) {
		let name = fname.split('.')[0];
		constant[name] = require('./constant/' + fname);
	}
	app.context.constant = constant;

    // 加载服务类
	let service = {};
	for (let fname of fs.readdirSync(__dirname + '/service')) {
		let name = fname.split('.')[0];
		service[name] = require('./service/' + fname);
	}
    app.context.service = service;

    // 把路由映射到js文件
	let controller = {};
	for (let fname of fs.readdirSync(__dirname + '/connector')) {
		let appModule = require('./connector/' + fname);
		let name = fname.split('.')[0];
		controller[name] = appModule;
		Object.keys(appModule).forEach(method => {
			router.all(`/${name}/${method}`, appModule[method]);
		})
	}
    // 渲染页面
    router.get('/view/:name',async(ctx,next)=>{   
        let name = ctx.params.name;  
        await ctx.render(name, {
            title:'hellow',
			user:ctx.passport
        })
    })



    // 应用路由
	app.use(router.routes())
    .use(router.allowedMethods());
}